package de.draufi.xml;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaders;

import de.draufi.logging.myLogger;

public class GPXReader {

	private Document doc = null;
	
	private Element root = null;
	private Element track = null;
	private GPXStrecke[] Segment = null;
	
	public GPXReader(File f) {
		try {
			SAXBuilder sb = new SAXBuilder(XMLReaders.NONVALIDATING);
			doc = (Document) sb.build(f);
		} catch (JDOMException e) {
			myLogger.getLog(this.getClass().getName()).severe(e.getMessage());
		} catch (IOException e) {
			myLogger.getLog(this.getClass().getName()).severe(e.getMessage());
		}
		if (doc == null){
			myLogger.getLog(this.getClass().getName()).warning("Error reading SAX-Document: " + f);
		} else {
			myLogger.getLog(this.getClass().getName()).info("using" + f);
			root = doc.getRootElement( );
			track = root.getChild("trk", root.getNamespace());	
			List<Element> l = track.getChildren("trkseg", root.getNamespace());
			if (l.size()>0) {
				Segment = new GPXStrecke[l.size()];
				for (int i=0; i<l.size(); i++){
					Segment[i] = new GPXStrecke(l.get(i), root);
				}
			}
		}
	}
	
	public void getTrack(){
		if (Segment != null) {
			myLogger.getLog(this.getClass().getName()).fine("Track enthaelt " + Segment.length + " Abschnitt(e).");
			for (int i=0; i < Segment.length; i++) {
				myLogger.getLog(this.getClass().getName()).fine("Abschnitt " + (i+1) + " besteht aus " + Segment[i].getAnzahlWegpunkte() + " Wegpunkten.");
			}
		} else {
			myLogger.getLog(this.getClass().getName()).fine("keine Tracks gefunden");
		}
	}

	public GPXStrecke getStrecke(int i){
		return Segment[i];
	}
}
